package com.lyf.network.learn.bionio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author LYF
 * @date 2022/6/27
 */
public class BioServer {
    public static void main(String[] args) throws IOException {
        System.out.println("server start");
        ServerSocket server = new ServerSocket(8888);

        while(true){

            Socket socket = server.accept();
            System.out.println("connected..."+socket.getRemoteSocketAddress());
            InputStream is = socket.getInputStream();
            //System.out.println("read bytes num is ::"+is.read());
            System.out.println("read data:::");
            int len = 0;
            byte []data = new byte[1024];
            BufferedInputStream bufferedInputStream = new BufferedInputStream(is);

             len = bufferedInputStream.read(data);

           // len = is.read(data);
//        while ((len=is.read(data))!=-1){
            System.out.println(new String(data,0,len));
//        }

            //is.close();

            System.out.println("resp:::");
            OutputStream os = socket.getOutputStream();
            // 写入HTTP协定响应头,固定写法
            os.write("HTTP/1.1 200 OK\r\n".getBytes());
            os.write("Content‐Type:text/html\r\n".getBytes());
            // 必须要写入空行,否则浏览器不解析
            os.write("\r\n".getBytes());

            os.write(("hello"+socket.getRemoteSocketAddress()).getBytes(StandardCharsets.UTF_8));

            is.close();
            os.close();
            socket.close();
        }
    }
}
